package com.vinoxm.rss.service;

import com.vinoxm.common.base.result.BaseResult;
import com.vinoxm.common.base.result.DataResult;
import com.vinoxm.common.core.service.BaseService;
import com.vinoxm.rss.dao.RssTrackerDao;
import com.vinoxm.rss.model.RssTracker;
import com.vinoxm.rss.redis.RedisClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RssTrackerService extends BaseService<RssTrackerDao> {

    private List<RssTracker> getTrackerList() {
        List<RssTracker> list = RedisClient.getTrackerList();
        return null == list ? RedisClient.setTrackerList(baseDao.selAll()): list;
    }

    public List<RssTracker> saveTrackers(List<RssTracker> trackers) {
        final List<RssTracker> trackerList = getTrackerList();
        List<RssTracker> include = trackers.stream().filter(t -> !trackerList.contains(t)).collect(Collectors.toList());
        if (include.size() > 0) {
            Long maxId = baseDao.selMaxTrackerId();
            for (int i = 0; i < include.size(); i++) {
                include.get(i).setId(i + maxId + 1);
            }
            if (baseDao.insertManyTrackerWithId(include) > 0) {
                return RedisClient.setTrackerList(baseDao.selAll());
            }
        }
        return getTrackerList();
    }

    public BaseResult getAllTracker() {
        return DataResult.Success(getTrackerList());
    }
}
